using System;
using System.Web;
using System.Web.Compilation;
using System.Web.Routing;
using System.Web.UI;

public class WebFormsRouteHandler<T> : IRouteHandler where T : class, IHttpHandler
{
	private string virtualPath;

	public WebFormsRouteHandler(string virtualPath)
	{
		this.virtualPath = virtualPath;
	}

	public IHttpHandler GetHttpHandler(RequestContext requestContext)
	{
		var view = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof (Page)) as T;
		foreach (var pair in requestContext.RouteData.Values)
		{
			if (pair.Key == "queryString") continue;
			SetDisplayProperty(view, pair.Key, pair.Value);
		}
		return HandleSpecialCases(view, requestContext);
	}

	protected virtual IHttpHandler HandleSpecialCases(T view, RequestContext requestContext)
	{
		return view;
	}

	private void SetDisplayProperty(T display, string key, object value)
	{
		var type = typeof (T);
		var pi = type.GetProperty(key);
		if (pi == null)
			throw new ArgumentException(string.Format("Handler {0} doesn't declare property {1} needed for routing.", type, key));
		pi.SetValue(display, Convert.ChangeType(value, pi.PropertyType), null);
	}
}